package com.csht.facelib.db;

import android.util.Log;
import java.util.List;

public class DbManager {
    //eq相等 ne、neq不相等， gt大于， lt小于 gte、ge大于等于 lte、le 小于等于 not非 mod求模 等
    private static final String TAG = DbManager.class.getSimpleName();
    private DaoManager mManager;
    private static DbManager dbManager = new DbManager();

    public static DbManager getInstance() {
        return dbManager;
    }

    private DbManager(){
        mManager = DaoManager.getInstance();
    }

    /**
     * 完成meizi记录的插入，如果表未创建，先创建Meizi表
     * @param user
     * @return
     */
    public boolean insertUser(User user){
        boolean flag = false;
        flag = mManager.getDaoSession().getUserDao().insert(user) != -1;
        Log.i(TAG, "insert Meizi :" + flag + "-->" + user.toString());
        return flag;
    }

    /**
     * 插入多条数据，在子线程操作
     * @param users
     * @return
     */
    public boolean insertUsers(final List<User> users) {
        boolean flag = false;
        try {
            mManager.getDaoSession().runInTx(new Runnable() {
                @Override
                public void run() {
                    for (User user : users) {
                        mManager.getDaoSession().insertOrReplace(user);
                    }
                }
            });
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 修改一条数据
     * @param user
     * @return
     */
    public boolean updateUser(User user){
        boolean flag = false;
        try {
            mManager.getDaoSession().update(user);
            flag = true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 删除单条记录
     * @param user
     * @return
     */
    public boolean deleteUser(User user){
        boolean flag = false;
        try {
            //按照id删除
            mManager.getDaoSession().delete(user);
            flag = true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 删除所有记录
     * @return
     */
    public boolean deleteAll(){
        boolean flag = false;
        try {
            //按照id删除
            mManager.getDaoSession().deleteAll(User.class);
            flag = true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 查询所有记录
     * @return
     */
    public List<User> queryAllUser(){
        return mManager.getDaoSession().loadAll(User.class);
    }

    /**
     * 根据主键id查询记录
     * @param key
     * @return
     */
    public User queryUserById(long key){
        return mManager.getDaoSession().load(User.class, key);
    }

}